<?php
require '../../include/library.inc.php';
require '../../include/admin_login.inc.php';
require '../../include/paging.inc.php';


# Ако запазваме
$_REQUEST["cat"] = 1;
if ($_POST['is_submitted']) {
    $error_message = '';

    //require "../../include/image_allowed_types.inc.php";
	
    if (!$_FILES['image']['name']) $error_message .= 'Не е избрана снимка!<br/>';

		
   /* if(!array_search($_FILES['image']['type'], $allowed_image_types) && $_FILES['image']['name']) $error_message .= 'Форматът на снимката не е позволен!<br/>';*/

	if(!$error_message) {
		define('IMAGE_WIDTH',GAL_IMAGE_WIDTH);
		define('IMAGE_HEIGHT', GAL_IMAGE_HEIGHT);
		define('THUMB_WIDTH',GAL_THUMB_WIDTH);
		define('THUMB_HEIGHT',GAL_THUMB_HEIGHT);
		
		include '../../include/image_man.php';
		$imn = new ImageManipulator;
		$upload_path = "../gallery/";
		
		if (is_uploaded_file($_FILES['image']['tmp_name'])) {
				
			$tmp_file = $_FILES['image']['tmp_name'];
			$exp = explode('.',$_FILES['image']['name']);
			$img_type = strtolower(end($exp));
			$imn -> decider($img_type,$tmp_file);
			///////////////////////////////////////////////
			
			$sql = 'SELECT MAX(order_number)+1 AS order_number FROM gallery';
			$row_number = mysql_fetch_assoc(query($sql));
		
			//Въвеждаме в базата данни
			$sql = "INSERT INTO gallery
					  (category_id,published, order_number)
					VALUES
					  ('".$_REQUEST["cat"]."', '".intval($_POST['published'])."', '".$row_number['order_number']."')
					  ";
			query($sql);
			$image_id = mysql_insert_id();
			$sql = 'SELECT lang_id,Name,code
				FROM
				language
				WHERE
				published
					';
			$result_lang = query($sql);
		
		while ($row_lang = mysql_fetch_object($result_lang)) {
			
				$em = $row_lang->lang_id;
				eval('$description =  $_POST[\'description_'.$em.'\'];');
				eval('$url =  $_POST[\'url_'.$em.'\'];');
				$sql = "INSERT INTO gallery_description
				  (image_id, lang_id, description, nav_url)
				VALUES
				  ('".$image_id."','".$em."','".escape($description)."','".escape($url)."')";
				 
				query($sql);
		}
			
			///////////////////////////////////////////////
			
			
			if(copy($tmp_file.'_image', $upload_path.'image_'.$image_id.'.'.$img_type) && copy($tmp_file.'_thumb', $upload_path.'th_image_'.$image_id.'.'.$img_type))
			{
				$sql = 'UPDATE gallery
						SET
							filename = \'image_'.$image_id.'.'.$img_type.'\'
						WHERE
							image_id = '.$image_id.'
						  ';
				query($sql);
				
			} else {
				
				$sql = 'DELETE FROM 
						   gallery
						WHERE
						   image_id = '.$image_id.'
						 ';
				query($sql);
				$_SESSION['message'] .= 'Грешка при качване на снимка. ';
				
			}	
			
		}
		
		redirect("images_gallery.php?cat=".$_REQUEST["cat"]);
	}
	
}


	   
	
	
head_admin("Галерия");
?>
<link href="../css/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../js/kipo.js"></script>

<script type="text/javascript">
	$(document).ready(function() {
		$("a[rel=gallery]").fancybox({
			'titlePosition' 	: 'over'
		});
	});
</script>

		
			<?php if ($error_message) { ?>
			<div class="message red">
				<h4>Грешка!</h4>
				<?=$error_message?>
			</div>
			<?php } ?>
			
			<?php if ($_SESSION['message']) { ?>
			<div class="message green">
				<?=$_SESSION['message']?>
			</div>
			<?php unset($_SESSION['message']); } ?>
      
            <div class="topbuttons">
                
            </div>
            
            <h3>Снимки за слайдшоу </h3>
			
			<form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
            <input type="hidden" name="is_submitted" value="1" />
            <input type="hidden" name="cat" value="<?=$_REQUEST["cat"]?>" />
            
            
            
			<dl class="clearfix">
            
            <dt><label for="image" class="required">Нова снимка <?=$row_cat['name']?></label></dt>
            <dd class="inline clearfix">
			<input class="inputbox" name="image" type="file" />
			<input type="submit" name="submit" id="submit" value="Качване">
			</dd>
           <?php
		    $sql_l = 'SELECT lang_id,Name,code
					FROM language
					WHERE published
					';
			$result = query($sql_l);
			
			$i=0;
			while ($row_lang = mysql_fetch_object($result)) {
		
				$em = $row_lang->lang_id;
				eval('$description =  $_POST[\'description_'.$em.'\'];');
				eval('$nav_url =  $_POST[\'url_'.$em.'\'];');
				?>
            <dt><label class="required">Описание на <?=$row_lang->Name?></label></dt>
            <dd><input class="inputbox w500" name="description_<?=$row_lang->lang_id?>" type="text" value="<?=sth($description)?>" ></dd>
            <dt><label class="required">URL за <?=$row_lang->Name?></label></dt>
            <dd><input class="inputbox w500" name="url_<?=$row_lang->lang_id?>" type="text" value="<?=sth($nav_url)?>" ></dd>
            
            <?php }?>
            
            </dl>
			</form>
            
            <table id="listing" width="100%" cellpadding="0" cellspacing="0">
			<thead>
				<tr>
               
					<td>Снимка</td>
                    
                    <?php
					 $sql_l = 'SELECT lang_id,Name,code
					FROM language
					WHERE published
					';
					$result_l = query($sql_l);
					while ($row_l = mysql_fetch_object($result_l)) {
                    echo '<td>Данни на '.$row_l->Name.'</td>';
					
					}
					?>
					<td>Действия</td>
				</tr>
			</thead>
			<tbody>
		<?php
		# Първоначално зареждане
		$lang = '1';
	
		$sql = "SELECT
					image_id,
					filename,
					published,
					order_number
					
				  FROM
					gallery
				WHERE category_id = '".$_REQUEST["cat"]."'
				 
				  
					";
		//$result = query($sql);
		if (!isset($_GET['sort'])) $_GET['sort'] = 1;
		if (!isset($_GET['sortBy'])) $_GET['sortBy'] = 4;
		//echo $paging->count();
		$paging = new Paging($sql, $_GET['sortBy'], $_GET['sort'], array(4=>"Подредба"), 15);
		$result = $paging->query();
		/*if ($paging->count() < ($_GET["frompage"]+1))
		{
			redirect("images_gallery.php");
		}*/
            while ($row = mysql_fetch_object($result)) {				  
        ?>
            <tr>
            
              
              <td><a href="<?=HTML_BASE?>gallery/<?=$row->filename?>"  rel="gallery">
			  <img src="<?=HTML_BASE?>gallery/th_<?=$row->filename?>" height="100"/></a></td>
              <?php
			  $sql_d = "SELECT lang_id,description,nav_url
					FROM gallery_description
					WHERE image_id = '".$row->image_id."'
					";
              $result_d = query($sql_d);
					while ($row_d = mysql_fetch_object($result_d)) {
						?>
                        <td> 
							<?=$row_d->description?><br />
							<a href="<?=$row_d->nav_url?>"><?=$row_d->nav_url?></a>
                        
                        </td>
                        <?php
                   
					}
              ?>
              
              
              <td class="icons">
              <a onClick="if (window.confirm('Сигурен ли си, че искаш да изтриеш тази снимка?')) { document.location='image_del.php?image_id=<?=$row->image_id?>&cat_id=<?=$cat_id?>'; return false; }" class="delete" title="Изтрий">Изтрий</a>
              </td>
              
              
            </tr>
         <?php } ?>				
			</tbody>
		</table>
        <div class="pagingwrap"><div class="paging">
			<?=$paging->display()?>
		</div></div>
            
<?php
	foot_admin(); 
?>